﻿<?php
App::uses('AppController', 'Controller');
App::uses('Area', 'Model');
App::uses('Line', 'Model');
App::uses('Moe', 'Model');
App::uses('Workstation', 'Model');
App::uses('WorkstationConfig', 'Model');
App::uses('CertificationDetail', 'Model');
App::uses('Certification', 'Model');
App::uses('Shift', 'Model');
App::uses('User', 'Model');
App::uses('UserArea', 'Model');
App::uses('UserTest', 'Model');
App::uses('Attempt', 'Model');
App::uses('Evaluation', 'Model');
App::uses('EvaluationDetail', 'Model');
App::uses('Theme', 'Model');
App::uses('TeamUser', 'Model');

class MigrationController extends AppController
{

    private $lines = array();
    private $moes = array();
    private $shifts = array();
    private $line = '5450151f-ac98-4777-86e4-15dc1b09678d';

    public function beforeFilter()
    {
        $this->Auth->allow();
        $this->loadModel('Area');
        $this->loadModel('Line');
        $this->loadModel('Moe');
        $this->loadModel('Shift');
        $this->loadModel('User');
        $this->loadModel('UserTest');
        $this->loadModel('TeamUser');
        $this->loadModel('Test');
        $this->loadModel('ShiftModels');
        $this->loadModel('UserLine');
        $this->loadModel('Workstation');
        $this->loadModel('WorkstationConfig');
        $this->loadModel('CertificationDetail');
        $this->loadModel('Certification');
        $this->loadModel('Certificate');
        $this->loadModel('Attempt');
        $this->loadModel('Evaluation');
        $this->loadModel('EvaluationDetail');
        $this->loadModel('Theme');
        $this->loadModel('UserArea');
        $this->loadModel('Link');
        parent::beforeFilter();
    }

    public function wss()
    {
        set_time_limit(360000);
        $this->request->allowMethod('get');
        $path = APP . WEBROOT_DIR . "/files/wss.csv";
        $handle = @fopen($path, "r");
        if ($handle) {
            $i = 0;
            while (($buffer = fgets($handle)) !== false) {
                $i++;
                if ($i < 376) {
                    continue;
                }
                $parts = explode(',', $buffer);
                $usr = array(
                    'id' => String::uuid(),
                    'category_id' => 'aa0ac014-02c0-11e4-995e-24b6fdfa405b',
                );
                $this->nomina($usr, trim($parts[2]));
                $this->name($usr, trim($parts[3]));
                $this->curp($usr, trim($parts[4]));
                $this->admissionDate($usr, trim($parts[5]));
                $usrLine = array();
                $usrLine['assign_date'] = '"' . $usr['admission_date'] . '"';
                $usrLine['days'] = $usr['days'];
                $this->level($usrLine, $usr, trim($parts[11]));
                $nomina = trim($parts[2]);
                $userBD = $this->User->getByNomina($nomina);
                if (isset($userBD['User']) === false) {
                    $r = $this->User->save($usr);
                    $this->User->clear();
                    if ($r === false) {
                        var_dump($usr);
                    }
                } else {
                    $usr = $userBD['User'];
                }
                $this->log($i . '---' . $nomina);
                //$this->UserLine->updateUserLine($usrLine, $usr['id'], $this->line);
                //return;
                //$this->evaluacion('5450151f-ac98-4777-86e4-15dc1b09678d', 'INICIAL', $usr, $parts[12], $parts[13], $parts[14], $parts[15], $parts[16], $parts[17], $parts[18], $parts[19], $parts[20], $parts[21]);
                //$this->evaluacion('5450151f-ac98-4777-86e4-15dc1b09678d', 'INTERMEDIO', $usr, $parts[22], $parts[23], $parts[24], $parts[25], $parts[26], $parts[27], $parts[28], $parts[29], $parts[30], $parts[31]);
                //$this->evaluacion('5450151f-ac98-4777-86e4-15dc1b09678d', 'AVANZADO', $usr, $parts[32], $parts[33], $parts[34], $parts[35], $parts[36], $parts[37], $parts[38], $parts[39], $parts[40], $parts[41]);
                //$this->evaluacion('5450151f-ac98-4777-86e4-15dc1b09678d', 'TWI', $usr, $parts[50], $parts[51], $parts[54], null, $parts[52], null, $parts[55], null, $parts[57], null);


                //Crimpado de terminal H
                $this->certification('54501645-c098-4246-9230-15dc1b09678d', $usr, $parts[59], $parts[60], $parts[61], $parts[62], $parts[63], $parts[64], $parts[65]);
                //Doblez de terminal H
                $this->certification('54501c77-7b58-4caf-93ff-15dc1b09678d', $usr, $parts[68], $parts[69], $parts[70], $parts[71], $parts[72], $parts[73], $parts[74]);
                //Moldeo IC Holder
                $this->certification('54501cd5-fe98-4488-80e1-15dc1b09678d', $usr, $parts[77], $parts[78], $parts[79], $parts[80], $parts[81], $parts[82], $parts[83]);
                //CORTE DE TERMINAL H
                $this->certification('54501e2e-a298-4411-9c89-15dc1b09678d', $usr, $parts[86], $parts[87], $parts[88], $parts[89], $parts[90], $parts[91], $parts[92]);
                //INSERCCION DE MAGNETO
                $this->certification('54501e5c-e098-4841-9029-15dc1b09678d', $usr, $parts[95], $parts[96], $parts[97], $parts[98], $parts[99], $parts[100], $parts[101]);
                //INSERCCION DE MAGNETO Y FLUX
                $this->certification('54501e70-f5b8-436c-8316-15dc1b09678d', $usr, $parts[104], $parts[105], $parts[106], $parts[107], $parts[108], $parts[109], $parts[110]);
                //DOBLEZ DE CHIP
                $this->certification('54501ea1-e458-4b68-b83f-15dc1b09678d', $usr, $parts[113], $parts[114], $parts[115], $parts[116], $parts[117], $parts[118], $parts[119]);
                /// Carga y descarga de mesa rotativa
                $this->certification('54501eb1-c158-48b7-9809-15dc1b09678d', $usr, $parts[122], $parts[123], $parts[124], $parts[125], null, null, null);
                /// Carga de chip
                $this->certification('54501eca-1738-4f76-8b29-15dc1b09678d', $usr, $parts[131], $parts[132], $parts[133], $parts[134], null, null, null);
                //Estaqueado de chip
                $this->certification('54501edd-8a38-44a6-8fe2-15dc1b09678d', $usr, $parts[140], $parts[141], $parts[142], $parts[143], $parts[144], $parts[145], $parts[146]);
                //Punteado de terminales
                $this->certification('54501eeb-b698-4991-85c9-15dc1b09678d', $usr, $parts[149], $parts[150], $parts[151], $parts[152], $parts[153], $parts[154], $parts[155]);
                //Sobremoldeo
                $this->certification('54501efb-46d8-4bfd-b8b6-15dc1b09678d', $usr, $parts[158], $parts[159], $parts[160], $parts[161], $parts[162], $parts[163], $parts[164]);
                /// Moldeo de stick
                $this->certification('54501f09-7c58-4e8f-8249-15dc1b09678d', $usr, $parts[167], $parts[168], $parts[169], $parts[170], null, null, null);
                //PRUEBA FUNCIONAL E INSERCCION DE OR IJNG
                $this->certification('54501f17-8098-47dd-b695-15dc1b09678d', $usr, $parts[176], $parts[177], $parts[178], $parts[179], $parts[180], $parts[181], $parts[182]);
                //INSPRECCION DE COMPONENTES
                $this->certification('54501f25-79b8-4a8b-9e53-15dc1b09678d', $usr, $parts[185], $parts[186], $parts[187], $parts[188], $parts[189], $parts[190], $parts[191]);
                //ENCINTADO
                $this->certification('54501f35-9b18-4b02-be35-15dc1b09678d', $usr, $parts[194], $parts[195], $parts[196], $parts[197], $parts[198], $parts[199], $parts[200]);
                //INSPECCION FINAL
                $this->certification('54501f56-8f78-4d76-89f1-15dc1b09678d', $usr, $parts[203], $parts[204], $parts[205], $parts[206], $parts[207], $parts[208], $parts[209]);
                //EMPAQUE FINAL
                $this->certification('54501f63-01f8-4a9f-960e-15dc1b09678d', $usr, $parts[212], $parts[213], $parts[214], $parts[215], $parts[216], $parts[217], $parts[218]);
                //ESTAMPADO DE CABLES
                $this->certification('54501f71-36f8-4c74-b8d3-15dc1b09678d', $usr, $parts[221], $parts[222], $parts[223], $parts[224], $parts[225], $parts[226], $parts[227]);
                //ENSAMBLE DE CONVOLUTE
                $this->certification('54501f7f-23b8-418b-821d-15dc1b09678d', $usr, $parts[230], $parts[231], $parts[232], $parts[233], $parts[234], $parts[235], $parts[236]);
                //ENSAMBLE DE CLIP
                $this->certification('54501f8f-feb8-4e65-b952-15dc1b09678d', $usr, $parts[239], $parts[240], $parts[241], $parts[242], $parts[243], $parts[244], $parts[245]);
                //ENSAMBLE DE FIBER GLASS
                $this->certification('54501fb0-9558-4670-8989-15dc1b09678d', $usr, $parts[248], $parts[249], $parts[250], $parts[251], $parts[252], $parts[253], $parts[254]);
                //ENSAMBLE DE PROTECTOR METALICO
                $this->certification('54501fc1-e078-4f02-9aff-15dc1b09678d', $usr, $parts[257], $parts[258], $parts[259], $parts[260], $parts[261], $parts[262], $parts[263]);
                //ENGARGOLADO DE BRACKET TOYOTA
                $this->certification('54501fd1-a398-4f3b-babc-15dc1b09678d', $usr, $parts[266], $parts[267], $parts[268], $parts[269], $parts[270], $parts[271], $parts[272]);
                //ENSAMBLE DE BRACKETS
                $this->certification('54501fdf-58b8-4daa-bd23-15dc1b09678d', $usr, $parts[275], $parts[276], $parts[277], $parts[278], $parts[279], $parts[280], $parts[281]);
                //ENSAMBLE DE CINTILLO
                $this->certification('54501feb-7ff8-4444-9a94-15dc1b09678d', $usr, $parts[284], $parts[285], $parts[286], $parts[287], $parts[288], $parts[289], $parts[290]);
                //MOVIMIENTO DE GROMMET
                $this->certification('54502001-37f8-41d6-85d5-15dc1b09678d', $usr, $parts[293], $parts[294], $parts[295], $parts[296], $parts[297], $parts[298], $parts[299]);
                //MARCADO LINEA
                $this->certification('54502054-97d8-4c52-bf1d-15dc1b09678d', $usr, $parts[302], $parts[303], $parts[304], $parts[305], $parts[306], $parts[307], $parts[308]);
                //INSPECCION DE ESTAMPADO DE LINEA
                $this->certification('54502064-86d8-432a-a34d-15dc1b09678d', $usr, $parts[311], $parts[312], $parts[313], $parts[314], $parts[315], $parts[316], $parts[317]);
                // Estaciones agregadas para la migracion del 30 Marzo 2015
                //ENSAMBLE DE CAP
                $this->certification('55198876-dc80-4c5d-bf51-12d01b09678d', $usr, $parts[320], $parts[321], $parts[322], $parts[323], $parts[324], $parts[325], $parts[326]);
                //ENSAMBLE DE BRACKET L8
                $this->certification('5519896b-d458-491d-ae26-12d01b09678d', $usr, $parts[329], $parts[330], $parts[331], $parts[332], $parts[333], $parts[334], $parts[335]);
                //ENSAMBLE DE FLANGE
                $this->certification('551989ef-acb0-467e-bfad-12d01b09678d', $usr, $parts[338], $parts[339], $parts[340], $parts[341], $parts[342], $parts[343], $parts[344]);
                break;
            }
            fclose($handle);
        }
        //$this->redirect(array('controller' => 'Cables', 'action' => 'index'));
        $this->set('title', __('Migracion MOE2 WSS'));
        $this->layout = 'base';
    }

    public function nomina(&$user, $value)
    {
        if (is_numeric($value) === true) {
            if (strlen($value) != 8) {
                var_dump($user['nomina'] . ' NOMINA MAL: ' . $value);
            }
        } else {
            $patron = '/^EXT[0-9]{4}/';
            $filter = preg_match($patron, $value);
            if ($filter !== 1) {
                $user['is_external'] = User::EXTERNAL_ON;
                var_dump(' NOMINA MAL: ' . $value);
            }
        }
        $value = $value == '' ? null : $value;
        $user['nomina'] = $value;
        $user['us3r'] = $value === null ? 'Temp' . rand(1, 10000) : $value;
    }

    public function name(&$user, $value)
    {
        $len = strlen($value);
        if ($len < 10) {
            var_dump($user['nomina'] . ' NOMBRE MUY CORTO: ' . $value);
        }
        $user['full_name'] = ($value);
    }

    public function curp(&$user, $value)
    {
        $len = strlen($value);
        if ($len < 18) {
            var_dump($user['nomina'] . ' CURP ERRONEA: ' . $value);
            $value = null;
        }
        $user['curp'] = $value;
        $user['p4ss'] = $value === null ? 'temporal' : $value;
    }

    public function admissionDate(&$user, $value)
    {
        $admissionDate = null;
        $currentDate = new DateTime();
        $user['days'] = 0;
        try {
            $dt = DateTime::createFromFormat('d/m/Y', $value);
            $interval = $currentDate->diff($dt, true);
            $admissionDate = $dt->format('Y-m-d');
            $user['days'] = $interval->format('%a');
        } catch (Exception $exc) {
            $this->log($user['nomina'] . ' FECHA DE INGRESO ERRONEA ' . $value);
        }
        $user['admission_date'] = $admissionDate;
    }

    public function level(&$usrLevel, $usr, $value)
    {
        $nameLevel = strtolower($value);
        $level = null;
        switch ($nameLevel) {
            case 'inicial':
                $level = '545035ae-bd98-4eae-9036-15dc1b09678d';
                break;
            case 'intermedio':
                $level = '545035d7-6af8-47c7-88dc-15dc1b09678d';
                break;
            case 'avanzado':
                $level = '545035ec-a498-44d5-b543-15dc1b09678d';
                break;
            case 'nada':
                $level = '54503623-a9f8-4ac5-807d-15dc1b09678d';
                break;
            case 'default':
                var_dump($usr['nomina'] . ' nivel erroneo ' . $value);
                $level = '54503623-a9f8-4ac5-807d-15dc1b09678d';
                break;
        }
        $usrLevel['level_excel'] = '"' . $level . '"';
    }

    public function certification($workstationId, $user, $ec, $ef, $vc, $vf, $gc, $cc, $cf)
    {
        $ec = trim($ec);
        $ef = trim($ef);
        $vc = trim($vc);
        $vf = trim($vf);
        $gc = trim($gc);
        $cc = trim($cc);
        $cf = trim($cf);

        if ($ec === '' && $vc === '' && ($gc === '' || $gc === null) && ($cc === '' || $cc === null)) {
            return;
        }
        $this->Workstation->id = $workstationId;
        $w = $this->Workstation->read();
        $workstationName = $w['Workstation']['description'];
        $cert = $this->Certification->getEnabledByUserAndWorkstation($user['id'], $workstationId);
        $certificationId = String::uuid();
        if (isset($cert['Certification']) === false) {
            $certificationData = array(
                'id' => $certificationId,
                'user_id' => $user['id'],
                'workstation_id' => $workstationId,
            );
            $this->Certification->save($certificationData);
            $this->Certification->clear();
        } else {
            $certificationId = $cert['Certification']['id'];
        }
        $def = null;
        $dvf = null;
        $dcf = null;
        if ($ec != '') {
            $ec = str_replace(',', '.', $ec);
            try {
                $def = DateTime::createFromFormat('d/m/Y', $ef);
                if ($def === false)
                    $def = null;
                else {
                    $def = $def->format('Y-m-d');
                }
                if (is_numeric($ec) === true) {
                    $wc = $this->WorkstationConfig->getByWorkstationAndName($workstationId, 'Evaluación en piso');
                    $detailData = array(
                        'id' => String::uuid(),
                        'certification_id' => $certificationId,
                        'workstation_config_id' => $wc['WorkstationConfig']['id'],
                        'qualification' => (double)$ec,
                        'certification_date' => $def,
                        'status' => 1,
                    );
                    $xxx1 = $this->CertificationDetail->save($detailData);
                    $this->CertificationDetail->clear();
                    $this->propagation($user['id'], $xxx1['CertificationDetail']);
                } else {
                    $msg = $user['nomina'] . ' ' . $workstationName . ' Evaluación CALIFICACION ERRONEA ' . $ec;
                    $this->log($msg, LOG_ERR);
                }
            } catch (Exception $exc) {
                $msg = $user['nomina'] . ' ' . $workstationName . ' Evaluación FECHA ERRONEA ' . $ef;
                $this->log($msg, LOG_ERR);
            }
        }
        if ($vc != '') {
            $vc = str_replace(',', '.', $vc);
            try {
                $dvf = DateTime::createFromFormat('d/m/Y', $vf);
                if ($dvf === false)
                    $dvf = null;
                else {
                    $dvf = $dvf->format('Y-m-d');
                }
                if (is_numeric($vc) === true) {
                    $wc = $this->WorkstationConfig->getByWorkstationAndName($workstationId, 'Validación en piso');
                    $detailData = array(
                        'id' => String::uuid(),
                        'certification_id' => $certificationId,
                        'workstation_config_id' => $wc['WorkstationConfig']['id'],
                        'qualification' => (double)$vc,
                        'certification_date' => $dvf,
                        'status' => 1,
                    );
                    $xxx2 = $this->CertificationDetail->save($detailData);
                    $this->CertificationDetail->clear();
                    $this->propagation($user['id'], $xxx2['CertificationDetail']);
                } else {
                    $msg = $user['nomina'] . ' ' . $workstationName . ' Validación CALIFICACION ERRONEA ' . $vc;
                    $this->log($msg, LOG_ERR);
                }
            } catch (Exception $exc) {
                $msg = $user['nomina'] . ' ' . $workstationName . ' validación FECHA ERRONEA ' . $vf;
                $this->log($msg, LOG_ERR);
            }
        }
        if ($cc != '') {
            $cc = str_replace(',', '.', $cc);
            try {
                $dcf = DateTime::createFromFormat('d/m/Y', $cf);
                if ($dcf === false)
                    $dcf = null;
                else {
                    $dcf = $dcf->format('Y-m-d');
                }
                if (is_numeric($cc) === true) {
                    $wc = $this->WorkstationConfig->getByWorkstationAndName($workstationId, 'Certificación en piso');
                    $detailData = array(
                        'id' => String::uuid(),
                        'certification_id' => $certificationId,
                        'workstation_config_id' => $wc['WorkstationConfig']['id'],
                        'qualification' => (double)$cc,
                        'certification_date' => $dcf,
                        'status' => 1,
                    );
                    $xxx3 = $this->CertificationDetail->save($detailData);
                    $this->CertificationDetail->clear();
                    $this->propagation($user['id'], $xxx3['CertificationDetail']);
                } else {
                    $msg = $user['nomina'] . ' ' . $workstationName . ' Certificación CALIFICACION ERRONEA ' . $cc;
                    $this->log($msg, LOG_ERR);
                }
            } catch (Exception $exc) {
                $msg = $user['nomina'] . ' ' . $workstationName . ' Certificación FECHA ERRONEA ' . $vf;
                $this->log($msg, LOG_ERR);
            }
        }
        if ($gc != '') {
            $gc = str_replace(',', '.', $gc);
            try {
                $dcf = DateTime::createFromFormat('d/m/Y', $cf);
                if ($dcf === false)
                    $dcf = null;
                else {
                    $dcf = $dcf->format('Y-m-d');
                }
                if (is_numeric($cc) === true) {
                    $wc = $this->WorkstationConfig->getByWorkstationAndName($workstationId, 'Generales');
                    $detailData = array(
                        'id' => String::uuid(),
                        'certification_id' => $certificationId,
                        'workstation_config_id' => $wc['WorkstationConfig']['id'],
                        'qualification' => (double)$gc,
                        'certification_date' => $dcf,
                        'status' => 1,
                    );
                    $xxx4 = $this->CertificationDetail->save($detailData);
                    $this->CertificationDetail->clear();
                    $this->propagation($user['id'], $xxx4['CertificationDetail']);
                } else {
                    $msg = $user['nomina'] . ' ' . $workstationName . ' Certificación CALIFICACION ERRONEA ' . $cc;
                    $this->log($msg, LOG_ERR);
                }
            } catch (Exception $exc) {
                $msg = $user['nomina'] . ' ' . $workstationName . ' Certificación FECHA ERRONEA ' . $vf;
                $this->log($msg, LOG_ERR);
            }
        }
        if ($def || $dvf || $dcf) {
            $a = array();
            if ($def !== null) {
                $a[] = $def;
            }
            if ($dvf !== null) {
                $a[] = $dvf;
            }
            if ($dcf !== null) {
                $a[] = $dcf;
            }
            usort($a, function ($d, $d2) {
                return $d > $d2;
            });
            $s = $a[0];
            $x = end($a);
            $l = new DateTime($x);
            $l->add(new DateInterval('P' . $w['Workstation']['life'] . 'D'));
            $this->Certification->id = $certificationId;
            $certificationData = array();
            $certificationData['start'] = $s;
            $certificationData['life'] = $l->format('Y-m-d');
            $certificationData['end'] = $x;
            $this->Certification->save($certificationData);
            $this->Certification->clear();
        }
    }

    private function propagation($userId, $certificationDetailSource)
    {
        $certificationDetailSourceId = $certificationDetailSource['id'];
        $workstationConfigSourceId = $certificationDetailSource['workstation_config_id'];
        $this->WorkstationConfig->id = $workstationConfigSourceId;
        /**
         * Leemos la certificacion que desato la propagacion. Esta certificacion
         * siempre existe.
         * Obtenemos todos los detalles de certificaciones que dependen de este
         * detalle de certificacion
         */
        $links = $this->Link->getByDestination($workstationConfigSourceId);
        foreach ($links as $link) {
            /**
             * $link contiene una parte de la certificacion que se genera por propagacion
             * Obtenemos la parte de la certificacion que se va crear por propagacion
             */
            $this->WorkstationConfig->id = $link['source'];
            $workstationConfig = $this->WorkstationConfig->read();
            $this->WorkstationConfig->clear();
            /**
             * Obtenemos la Operación de trabajo donde se generara la parte de la certificacion
             */
            $workstationId = $workstationConfig['WorkstationConfig']['workstation_id'];
            $qualificationAndDate = $this->Link->getPropagation($userId, $link['source']);
            $qualification = $qualificationAndDate[0]['qualification'];
            $certificationDate = $qualificationAndDate[0]['certification_date'];
            $certification = $this->Certification->getEnabledByUserAndWorkstation($userId, $workstationId);
            /**
             * Verificamos si ya existe la certificacion por propagacion
             */
            if (isset($certification['Certification']) === false) {
                /**
                 * Si no existe entonces generamos la certificacion "vacia".
                 */
                $newCertificationId = String::uuid();
                $dataCertification = array(
                    'id' => $newCertificationId,
                    'user_id' => $userId,
                    'workstation_id' => $workstationId,
                );
                $this->Certification->save($dataCertification);
                $this->Certification->clear();
                $this->createDetails($link['source'], $certificationDetailSourceId, $newCertificationId, $qualification, $certificationDate);
            } else {
                $certificationSourceId = $certification['Certification']['id'];
                $workstationConfigId = $link['source'];
                $certificationDetail = $this->CertificationDetail->getByCertificationAndWorkstationConfig($certificationSourceId, $workstationConfigId);
                if (isset($certificationDetail['CertificationDetail']) === false) {
                    $this->createDetails($link['source'], $certificationDetailSourceId, $certificationSourceId, $qualification, $certificationDate);
                } else {
                    $this->CertificationDetail->updateQualificationAndDate($certificationDetail['CertificationDetail']['id'], $qualification, $certificationDate);;
                }
            }
        }
    }

    public function createDetails($workstationConfigId, $certificationDetailSourceId, $newCertificationId, $qualification, $certificationDate)
    {
        $dataCertificationDetail = array(
            'workstation_config_id' => $workstationConfigId,
            'certification_id' => $newCertificationId, // Nueva certificacion generada por la propagacion
            'qualification' => $qualification,
            'certification_date' => $certificationDate,
            'source' => $certificationDetailSourceId,
        );
        $this->CertificationDetail->save($dataCertificationDetail);
        $this->CertificationDetail->clear();
    }

    public function evaluacion($lineId, $testName, $usr, $t1, $t2, $t3, $t4, $aq1, $ad1, $aq2, $ad2, $aq3, $ad3)
    {
        $test = $this->Test->getByNameAndLine($testName, $lineId);
        $testId = $test['Test']['id'];
        if ($aq1 === '') {
            if ($t1 === 'nok')
                $t1 = null;
            if ($t2 === 'nok')
                $t2 = null;
            if ($t3 === 'nok')
                $t3 = null;
            if ($t4 === 'nok')
                $t4 = null;
        }
        if ($t1 !== null)
            $t1 = trim($t1);
        if ($t2 !== null)
            $t2 = trim($t2);
        if ($t3 !== null)
            $t3 = trim($t3);
        if ($t4 !== null)
            $t4 = trim($t4);
        if (($t1 === '' || $t1 === null) && ($t2 === '' || $t2 === null) && ($t3 === '' || $t3 === null) && ($t4 === '' || $t4 === null)) {
            return;
        }
        $evaluationId = String::uuid();
        $evaluationData = array(
            'id' => $evaluationId,
            'user_id' => $usr['id'],
            'test_id' => $testId,
            'start' => null,
            'end' => null,
            'life' => null,
            'status' => 1,
            'success' => 0,
            'training' => 0,
        );
        $this->Evaluation->save($evaluationData);
        $this->Evaluation->clear();
        if ($t1 != null) {
            $t1 = strtolower($t1) === 'ok' ? 100 : 0;
            $this->addTheme($t1, $evaluationId, $testId, 0);
        }
        if ($t2 != null) {
            $t2 = strtolower($t2) === 'ok' ? 100 : 0;
            $this->addTheme($t2, $evaluationId, $testId, 1);
        }
        if ($t3 != null) {
            $t3 = strtolower($t3) === 'ok' ? 100 : 0;
            $this->addTheme($t3, $evaluationId, $testId, 2);
        }
        if ($t4 != null) {
            $t4 = strtolower($t4) === 'ok' ? 100 : 0;
            $this->addTheme($t4, $evaluationId, $testId, 3);
        }
        $this->addAttempt($evaluationId, $aq1, $ad1, $usr, $testName);
        $this->addAttempt($evaluationId, $aq2, $ad2, $usr, $testName);
        $this->addAttempt($evaluationId, $aq3, $ad3, $usr, $testName);
    }

    private function addTheme($t1, $evaluationId, $testId, $i)
    {
        $theme = $this->Theme->getByTestAndOrden($testId, $i);
        $detailData = array(
            'id' => String::uuid(),
            'theme_id' => $theme['Theme']['id'],
            'evaluation_id' => $evaluationId,
            'qualification' => $t1,
            'evaluation_date' => null, // Desconocemos la fecha cuando se evaluo
        );
        $this->EvaluationDetail->save($detailData);
        $this->EvaluationDetail->clear();
    }

    private function addAttempt($evaluationId, $cal, $date, $usr, $testName)
    {
        $cal = str_replace(',', '.', $cal);
        if ($cal === null)
            return;
        $cal = trim($cal);
        if ($cal === '')
            return;
        $cal = ($cal === 'OK' ? 100 : $cal);
        if (is_numeric($cal) === true) {
            $d = DateTime::createFromFormat('d/m/Y', $date);
            $attemptData = array(
                'id' => String::uuid(),
                'evaluation_id' => $evaluationId,
                'application_date' => $d ? $d->format('Y-m-d') : null,
                'qualification' => (double)$cal,
                'status' => 1,
            );
            if ($attemptData['application_date'] === null) {
                $msg = $usr['nomina'] . ' ' . $testName . ' FECHA ERRONEA ' . $date;
                $this->log($msg, LOG_ERR);
            }
            $this->Attempt->save($attemptData);
            $this->Attempt->clear();
        } else {
            $msg = $usr['nomina'] . ' ' . $testName . ' CALIFICACION ERRONEA ' . $cal;
            $this->log($msg, LOG_ERR);
        }
    }

    public function line(&$user, $value)
    {
        $lineId = null;
        if (isset($this->lines[$value]) === false) {
            $this->lines[$value] = $this->Line->getByName($value);
        }
        if (isset($this->lines[$value]['Line']) === true) {
            $lineId = $this->lines[$value]['Line']['id'];
        } else {
            switch (mb_strtoupper($value)) {
//                case 'NUEVO INGRESO':
//                    $user['status'] = User::STATUS_NEW;
//                    break;
                case 'SOPORTE':
                    $user['support'] = User::SUPPORT_ON;
                    break;
                case 'FX':
                    $user['shift_id'] = 'c7e01477-f801-11e3-9113-fc4dd44a2aac'; // Turno flexible
                    break;
            }
            var_dump($user['nomina'] . ' LINEA ERRONEA: ' . $value);
        }
        $user['line_id'] = $lineId;
    }

    public function moe(&$user, $value)
    {
        $moeId = null;
        if (isset($this->moes[$value]) === false) {
            $this->moes[$value] = $this->Moe->getByName($value);
        }
        if (isset($this->moes[$value]['Moe']) === true) {
            $moeId = $this->moes[$value]['Moe']['id'];
        } else {
            var_dump($user['nomina'] . ' MOE ERRONEO: ' . $value);
        }
        $user['moe_id'] = $moeId;
    }

    public function shift(&$user, $value)
    {
        $shiftId = null;
        if (isset($this->shifts[$value]) === false) {
            $this->shifts[$value] = $this->Shift->getByName($value);
        }
        if (isset($this->shifts[$value]['Shift']) === true) {
            $shiftId = $this->shifts[$value]['Shift']['id'];
        } else {
            switch (mb_strtoupper($value)) {
                case 'I':
                    $user['status'] = User::STATUS_INCAPACIDAD;
                    break;
                case 'S':
                    $user['support'] = User::SUPPORT_ON;
                    break;
            }
            var_dump($user['nomina'] . ' TURNO ERRONEO: ' . $value);
        }
        $user['shift_id'] = $shiftId;
    }

}
